package org.groupg.practice.guava;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class ListenableFutureExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);

        ListenableFuture<String> future = listeningExecutorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // 模拟异步任务
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + ": 异步任务执行完毕");
                return "异步任务执行成功: success";
            }
        });

        Futures.addCallback(future, new com.google.common.util.concurrent.FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                // 异步任务执行成功后的回调方法
                System.out.println(Thread.currentThread().getName() + ": 异步任务执行成功, 结果是: " + result);
                listeningExecutorService.shutdown(); // 收到回调结果后，建议关注线程池，否则监听回调程序会一直阻塞，不会结束
            }

            @Override
            public void onFailure(Throwable t) {
                // 异步任务执行失败后的回调方法
                System.out.println("异步任务执行失败");
                t.printStackTrace();
            }
        }, executorService);

        System.out.println(Thread.currentThread().getName() + ": 主线程继续执行其他任务...");
    }
}